package com.accp.hotevent.interceptor;

import com.accp.hotevent.entity.User;
import com.accp.hotevent.util.LoggedUserContext;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS请求不做校验,
        // 前后端分离的架构, 前端会发一个OPTIONS请求先做预检, 对预检请求不做校验
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader("token");

        log.info("进入AdminInterceptor..."+request.getRequestURI());
        log.info("token:{}",token);
        if(StringUtil.isNullOrEmpty(token)){
//            throw new RuntimeException("token不能为空");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        User user = (User) redisTemplate.opsForValue().get(token);
        if(user == null){
//            throw new RuntimeException("token失效");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        if(!user.isAdmin()){
            log.warn("非法的操作");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        LoggedUserContext.setCurrentLoggedUser(user);
        log.info("通过AdminInterceptor");
        return true;
    }
}
